<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.userId"
            clearable
            placeholder="请输入userId"
            style="width: 230px"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkId"
            clearable
            placeholder="请输入推广链接id"
            style="width: 230px"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <el-button type="primary" @click="clickExport">数据导出</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column label="链接id" prop="referralLinkId" minWidth="110"></el-table-column>
      <el-table-column label="userId" prop="userId" minWidth="110"></el-table-column>
      <el-table-column label="激励广告点击次数IPU" prop="advertNum" minWidth="120"></el-table-column>
      <el-table-column label="激励广告收入ARPU" prop="ecpmCost" minWidth="120">
        <template #default="{ row }">
          <span>{{ `${organizeDigital(row.ecpmCost / 1000, 6)}元` }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平均eCPM" prop="avgEcpm" minWidth="120"></el-table-column>
      <el-table-column label="最大eCPM" prop="maxEcpm" width="120"></el-table-column>
      <el-table-column label="系统平台" prop="devicePlatform" width="90"></el-table-column>
      <el-table-column label="回传状态" prop="reportBackStatus" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.reportBackStatus === 0" key="el-tag-1" type="primary">没有上报</el-tag>
          <el-tag v-else-if="row.reportBackStatus === 1" key="el-tag-2" type="success">上报成功</el-tag>
          <el-tag v-else-if="row.reportBackStatus === 2" key="el-tag-3" type="danger">上报失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告回传时间" prop="backTime" minWidth="140"></el-table-column>
      <el-table-column label="用户买入时间" prop="userRegisterTime" minWidth="140"></el-table-column>
      <el-table-column label="备注" prop="remark" minWidth="180"></el-table-column>
      <el-table-column fixed="right" label="操作" headerAlign="center" align="center" prop="action" width="110">
        <template #default="{ row }">
          <el-button
            v-if="row.reportBackStatus !== 1"
            class="butt"
            link
            :icon="IconEdit"
            :disabled="row.__syncBackLoading"
            :loading="row.__syncBackLoading"
            type="primary"
            @click="iaaReportOrderBack(row)"
          >
            手动回传
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconEdit from '~icons/ep/edit';
  const { proxy } = getCurrentInstance() as any;
  import {
    type IaaLinkBackRecordItem,
    type IaaLinkBackRecordRequest,
    getIaaLinkBackRecord,
    iaaReportOrderBackAxios,
    tradeOrderIaaBackRecordExcel,
  } from '@/api/marketing-management';
  import { easeDownloadFile } from '@/utils/common.ts';
  import { organizeDigital } from '@/utils/numb';
  const dataRange = ref<[string, string] | undefined>();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const filterData = ref<IaaLinkBackRecordRequest>({
    current: 1,
    size: 40,
    referralLinkId: undefined,
    userId: undefined,
  });
  type _TableItem = IaaLinkBackRecordItem & {
    __syncBackLoading?: boolean;
  };

  const tableData: Ref<_TableItem[]> = ref([]);
  const description = ref('');

  onMounted(() => {
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
  });

  /** 手动回传 */
  async function iaaReportOrderBack(row: _TableItem) {
    try {
      row.__syncBackLoading = true;
      await iaaReportOrderBackAxios(row.iaaEcpmBackId!);
      row.__syncBackLoading = false;
      ElToast.success('回传成功');
      getAxiosData(false);
    } catch (error) {
      row.__syncBackLoading = false;
      ElToast.error(error.msg || `回传失败，-BD004`);
    }
  }

  /** 数据导出 */
  const clickExport = async () => {
    const res = await tradeOrderIaaBackRecordExcel(filterData.value);
    easeDownloadFile(res, 'IAA回传记录数据');
  };

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      if (Array.isArray(dataRange.value) && dataRange.value.length) {
        filterData.value.startDate = `${dataRange.value[0]} 00:00:00`;
        filterData.value.endDate = `${dataRange.value[1]} 23:59:59`;
      } else {
        filterData.value.startDate = '';
        filterData.value.endDate = '';
      }
      const data = { ...filterData.value };
      const res = await getIaaLinkBackRecord({
        ...data,
      });
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
